package com.tcr.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;

import com.tcr.common.TcProject;

public class ProjectMapDao {

	@SuppressWarnings("finally")
	public static boolean addLinked(int uid, int pid) {
		Connection conn = null;
		boolean b = false;

		try {
			conn = dbutil.pool.getConnection();
			PreparedStatement ps = conn.prepareStatement(SqlString.add_map);
			ps.setInt(1, uid);
			ps.setInt(2, pid);
			int res = ps.executeUpdate();
			b = (res != 0);

		} catch (Exception ex) {
			logger.error(ex);
		} finally {
			if (conn != null)
				dbutil.pool.backConn(conn);
			return b;
		}
	}

	@SuppressWarnings("finally")
	public static boolean delLinkByUid(int uid) {
		Connection conn = null;
		boolean b = false;

		try {
			conn = dbutil.pool.getConnection();
			PreparedStatement ps = conn
					.prepareStatement(SqlString.del_map_byuid);
			ps.setInt(1, uid);
			int res = ps.executeUpdate();
			b = (res != 0);
		} catch (Exception ex) {
			logger.error(ex);
		} finally {
			if (conn != null)
				dbutil.pool.backConn(conn);
			return b;
		}
	}

	@SuppressWarnings("finally")
	public static List<TcProject> getProjsByUid(int uid) {
		Connection conn = null;
		List<TcProject> projs = new ArrayList<TcProject>();
		try {
			conn = dbutil.pool.getConnection();
			PreparedStatement ps = conn
					.prepareStatement(SqlString.getProjectByUid);
			ps.setInt(1, uid);
			ResultSet res = ps.executeQuery();
			while (res.next()) {
				int pid = res.getInt(1);
				String p_name = res.getString(2);
				int p_code = res.getInt(3);

				projs.add(new TcProject(pid, p_name, p_code));
			}

		} catch (Exception ex) {
			logger.error(ex);
		} finally {
			if (conn != null)
				dbutil.pool.backConn(conn);
			return projs;
		}
	}

	private final static DbUtil dbutil = DbUtil.getInstance();
	private final static Logger logger = Logger.getLogger(ProjectMapDao.class);

}
